package com.zxw.mallafter.api;

import com.zxw.mallafter.model.AdminExtend;
import com.zxw.mallafter.service.AdminService;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import util.PageInfo;

import java.util.List;
import java.util.Map;

/**
 * 对管理员进行操作
 */
@RestController
@RequestMapping(value = "/api/v1/admin", produces = "application/json;charset=utf-8")
public class Adminapi {
    private static final PasswordEncryptor encryptor = new StrongPasswordEncryptor();

    private AdminService adminService;
    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    //增
    @GetMapping
    public Map<String, Object> getall(@RequestParam(defaultValue = "1") Integer pageNo,
                                      @RequestParam(defaultValue = "2147483647") Integer pageSize,
                                      AdminExtend adminExtend) {

            if (pageNo == null || pageNo < 1) {
                pageNo = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = Integer.MAX_VALUE;
            }
        PageInfo pageInfo = new PageInfo(pageNo,pageSize);
        //UploadFileApiSystem.out.println("pageNo:"+pageNo+"pageSize:"+pageSize);
        List<AdminExtend> getall = adminService.getall(pageInfo, adminExtend);
        com.github.pagehelper.PageInfo<AdminExtend>
                page = com.github.pagehelper.PageInfo.of(getall);
        Map<String,Object> pi= Map.of("total",page.getTotal(),"pageNo",page.getPageNum(),"pageSize",page.getPageSize());


        return Map.of("success",true,"data",getall,"pi",pi);
    }
    //删除
    @DeleteMapping
    public ResponseEntity<Map<String,Object>> delete(@RequestBody Integer[] ids){
        int delete = adminService.delete(ids);
        return ResponseEntity.ok().body(Map.of("success",delete>0));
    }
    //增加
    @PostMapping
    public ResponseEntity<Map<String,Object>> insert(@RequestBody AdminExtend adminExtend){
        //加密
        adminExtend.setPassword(encryptor.encryptPassword(adminExtend.getPassword()));
        int insert = adminService.insert(adminExtend);
        return ResponseEntity.ok().body(Map.of("success",insert>0));
    }
    //修改
    @PutMapping
    public ResponseEntity<Map<String,Object>> update(@RequestBody AdminExtend adminExtend){
        if(adminExtend.getBirthday()!=null){
            adminExtend.setBirthday(adminExtend.getBirthday().plusDays(1));
        }
        //加密
        if(adminExtend.getPassword()!=null){
            adminExtend.setPassword(encryptor.encryptPassword(adminExtend.getPassword()));
        }
        int update = adminService.update(adminExtend);
        return ResponseEntity.ok().body(Map.of("success",update>0));
    }



}
